package cn.syy.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.syy.constants.Constants;
import cn.syy.constants.GlobalExceptionCode;
import cn.syy.feign.AppLoginFeignClient;
import cn.syy.mapper.CustomerMapper;
import cn.syy.pojo.domain.Customer;
import cn.syy.pojo.domain.CustomerSummary;
import cn.syy.pojo.domain.CustomerWallet;
import cn.syy.pojo.param.RegisterSaveLoginParam;
import cn.syy.service.ICustomerService;
import cn.syy.template.AppWeChatTemplate;
import cn.syy.utils.AssertUtil;
import cn.syy.utils.BitStatesUtil;
import cn.syy.utils.NameUtil;
import cn.syy.utils.SmsUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.math.BigDecimal;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;




/**
 * <p>
 * 客户 服务实现类
 * </p>
 *
 * @author sysyy
 * @since 2024-07-31
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {
    @Autowired
    private AppWeChatTemplate appWeChatTemplate;

    @Autowired
    private AppLoginFeignClient appLoginFeignClient;

    @Autowired
    private CustomerSummaryServiceImpl customerSummaryService;

    @Autowired
    private CustomerWalletServiceImpl customerWalletService;

    /**
     * 小程序乘客注册（包含手机号）
     * @param openIdCode
     * @param phoneCode
     */
    @Override
    public void registerIncludePhoneCode(String openIdCode, String phoneCode) {
        String openid = appWeChatTemplate.getOpenIdByCode(openIdCode);
        Customer customer = super.getOne(new QueryWrapper<Customer>().eq("open_id", openid)); // 通过openid获取到customer对象

        AssertUtil.isNull(customer, GlobalExceptionCode.PARAM_PHONE_EXIST); // 判断diver对象是否存在，存在就说名已经注册过了，就为空

        // 3. 业务实现
        // 3.1 将注册的乘客对象放到数据库
        String phoneNumber = appWeChatTemplate.getPhoneByAccessTokenAndCode(phoneCode);
        String name = NameUtil.getName();
        customer = new Customer();
        saveCustomerIncludePhone(customer,openid,phoneNumber,name);


        // 生成随机密码并发送短信告知客户
        SmsUtils.setPassword();
        String password = SmsUtils.getPassword();
//        SmsUtils.sendSms(phoneNumber,password);

        String encryptedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
        // 3.2将从表（配置，钱包，统计）进行初始化
        Long id = customer.getId();
        initCustomerAssociation(id,encryptedPassword);

        // 3.3 将登录信息保存到login数据库中
        saveLoginIncludePhone(openid,encryptedPassword,phoneNumber,name,id);
    }



    /**
     * 小程序乘客注册（不包含手机号）
     * @param openIdCode
     */
    @Override
    @Transactional
    public void register(String openIdCode) {
        String openid = appWeChatTemplate.getOpenIdByCode(openIdCode);
        Customer customer = super.getOne(new QueryWrapper<Customer>().eq("open_id", openid)); // 通过openid获取到customer对象
        AssertUtil.isNull(customer, GlobalExceptionCode.PARAM_PHONE_EXIST); // 判断diver对象是否存在，存在就说名已经注册过了，就为空
//         3. 业务实现
//         3.1 将注册的乘客对象放到数据库
        customer = new Customer();
        String name = NameUtil.getName();
        String phoneNumber = "15611810650"; // 设置接收短信的手机号
        customer.setPhone(phoneNumber);
        saveCustomerIncludePhone(customer,openid,phoneNumber,name);

        // 发送密码给手机号主人
        SmsUtils.setPassword();
        String password = SmsUtils.getPassword();
        // 3.2将从表（配置，钱包，统计）进行初始化
//        SmsUtils.sendSms(phoneNumber,password);
        String encryptedPassword = BCrypt.hashpw(password, BCrypt.gensalt());

        Long id = customer.getId();
        initCustomerAssociation(id,encryptedPassword);

        // 3.3 将登录信息保存到login数据库中
        saveLoginIncludePhone(openid,encryptedPassword,phoneNumber,name,id);

    }
    /**
     * 初始化乘客从表
     * @param id
     * @param password
     */
    private void initCustomerAssociation(Long id, String password) {
        CustomerSummary customerSummary = new CustomerSummary();
        customerSummary.setId(id);
        customerSummaryService.save(customerSummary);

        CustomerWallet customerWallet = new CustomerWallet();
        customerWallet.setId(id);
        customerWallet.setPassword(password);
        customerWalletService.save(customerWallet);
    }

    /**
     * 保存乘客数据到数据库
     * @param customer
     * @param openid
     * @param phoneNumber
     */

    private void saveCustomerIncludePhone(Customer customer, String openid, String phoneNumber,String name) {
        customer.setSex(0);
        customer.setPhone(phoneNumber);
        customer.setOpenId(openid);
        customer.setBitState(BitStatesUtil.OP_PHONE);
        customer.setName(name);
        super.save(customer);

    }

    /**
     * 存储注册乘客信息到uaa的login表里（包含手机号）
     * @param openid
     */
    private void saveLoginIncludePhone(String openid,String password,String phoneNumber,String name,Long id) {
        RegisterSaveLoginParam registerSaveLoginParam = new RegisterSaveLoginParam();
        registerSaveLoginParam.setUsername(name);
        registerSaveLoginParam.setPassword(password);
        registerSaveLoginParam.setType(Constants.Login.TYPE_CUSTOMER);
        registerSaveLoginParam.setEnabled(true); // 账号是否启用
        registerSaveLoginParam.setAvatar(Constants.AVATAR);
        registerSaveLoginParam.setAdmin(false); // 是否是管理员
        registerSaveLoginParam.setNickName(name);
        registerSaveLoginParam.setOpenId(openid);
        registerSaveLoginParam.setName(name);
        registerSaveLoginParam.setPhone(phoneNumber);
        registerSaveLoginParam.setId(id);
        appLoginFeignClient.save(registerSaveLoginParam);
    }


}
